//
//  LKTestpageNameViewController.m
//  YLHelper
//
//  Created by she1323 on 2018/5/9.
//  Copyright © 2018年 she1323. All rights reserved.
//

#import "LKTestpageNameViewController.h"
#import "LKTestPageNameDefaultCell.h"
#import "LKTestpageNameTitleCell.h"
#import "LKTestpageNameHeaderCell.h"
#import "LkTestpageNameBottomCell.h"
#import "LKTestpageNewBottomCell.h"
#import "LKTestpageNameCakeCell.h"
#import "LKTestDetailModel.h"
#import "LKTestChooseCell.h"
#import "LKTestAnswerCell.h"
#import "LKTestAnswerAnalysicCell.h"
#import "LKElearnViewController.h"
@interface LKTestpageNameViewController ()<UITableViewDataSource,UITableViewDelegate,UIScrollViewDelegate>{
    CGFloat currentOffset;
}

@property(nonatomic,strong)LKBaseTableview *tableview;
@property(nonatomic,strong)NSArray *titlesArray;
@property(nonatomic,strong)LKTestDetailModel *detailModel;
@property(nonatomic,strong)NSMutableArray *contentArray;
@property(nonatomic,strong)UIView *coverView;
@property(nonatomic,assign)BOOL showSomeOrAll;
@property(nonatomic,strong)NSMutableArray *qustionsArray;
@property(nonatomic,strong)NSArray *allQustionsArray;
@property(nonatomic,strong)UIButton *correctBtn;

@end

@implementation LKTestpageNameViewController
-(LKBaseTableview *)tableview{
    if (!_tableview) {
        _tableview = [LKBaseTableview setTableviewWithFrame:CGRectMake(0, NAVIGATION_BAR_HEIGHT, WIDTH , HEIGHT - NAVIGATION_BAR_HEIGHT) style:UITableViewStylePlain registercellClasss:@[@"LKTestPageNameDefaultCell",@"LKTestpageNameTitleCell",@"LKTestpageNameHeaderCell",@"LkTestpageNameBottomCell",@"LKTestpageNewBottomCell",@"LKTestpageNameCakeCell",@"LKTestAnswerAnalysicCell",@"LKTestAnswerCell",@"LKTestChooseCell"]];
        [self.view addSubview:_tableview];
        _tableview.delegate = self;
        _tableview.dataSource = self;
        _tableview.backgroundColor = [UIColor whiteColor];
        _tableview.estimatedRowHeight = 200;
        _tableview.estimatedSectionFooterHeight = 0;
        _tableview.estimatedSectionHeaderHeight = 200;
        _tableview.separatorStyle = UITableViewCellSeparatorStyleNone;
    }
    return _tableview;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.showSomeOrAll  = YES;
    [self.tableview reloadData];
    [self getTestpageDetailInformation];
    // Do any additional setup after loading the view.
}
-(void)setNavgationBackBtn{
    [super setNavgationBackBtn];
    self.backButton.hidden = YES;
    self.navigationItem.title = self.paperName;
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    [btn setTitle:@"关闭" forState:UIControlStateNormal];
    [btn setTitleColor:blueDefault forState:UIControlStateNormal];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:btn];
    [btn addTarget:self action:@selector(closeAction:) forControlEvents:UIControlEventTouchUpInside];
}

/**
 关闭
 @param btn 关闭按钮
 */
-(void)closeAction:(UIButton *)btn{
    for(UIViewController *controller in self.navigationController.viewControllers) {
        if([controller isKindOfClass:[LKElearnViewController class]]){
            [self.navigationController popToViewController:controller animated:YES];
        }
    }
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
//    return self.titlesArray.count + self.detailModel.paperQuestionDetail.count;
        return self.titlesArray.count + self.qustionsArray.count;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (section >= self.titlesArray.count) {
//        LKQuestionBankDetailModel *model = self.detailModel.paperQuestionDetail[section - self.titlesArray.count].questionBank;
//        return model.questionAnswer.count + 2;
        LKPaperQuestionDetailModel *detailModel = self.qustionsArray[section - self.titlesArray.count];
        LKQuestionBankDetailModel *bankDetailModel = detailModel.questionBank;
        return bankDetailModel.questionAnswer.count + 2;
    }
    return 1;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
        LKTestpageNameHeaderCell *cell = [tableView dequeueReusableCellWithIdentifier:@"LKTestpageNameHeaderCell"];
        cell.detailModel = self.detailModel;
        return cell;
    }
    if (indexPath.section == 1 || indexPath.section == 2 || indexPath.section == 3 || indexPath.section == 4) {
        LKTestPageNameDefaultCell *cell = [tableView dequeueReusableCellWithIdentifier:@"LKTestPageNameDefaultCell"];
        cell.titleLabel.text = self.titlesArray[indexPath.section];
        if (self.contentArray.count > 1) {
            cell.contentLabel.text = self.contentArray[indexPath.section - 1];
        }else{
            cell.contentLabel.text = @"";
        }
        return cell;
    }
      if (indexPath.section == 5) {
        LKTestpageNameCakeCell *cell = [tableView dequeueReusableCellWithIdentifier:@"LKTestpageNameCakeCell"];
          for (UIView *subView in cell.cakepieBgView.subviews) {
              [subView removeFromSuperview];
          }
        cell.detailModel = self.detailModel;
        return cell;
      }
     if (indexPath.section == 6) {
        LKTestpageNameTitleCell *cell = [tableView dequeueReusableCellWithIdentifier:@"LKTestpageNameTitleCell"];
        cell.timeLabel.text = @"";
         cell.showRightBtn = YES;
         [cell.corretBtn addTarget:self action:@selector(showSomeOrAll:) forControlEvents:UIControlEventTouchUpInside];
         cell.corretBtn.tag = 10000;
        cell.titleLabel.text = self.titlesArray[indexPath.section];
        cell.detailModel = self.detailModel;
         cell.corretBtn.selected = self.showSomeOrAll;
        return cell;
     }
    LKTestChooseCell *cell = [tableView dequeueReusableCellWithIdentifier:@"LKTestChooseCell"];
//    LKQuestionBankDetailModel *model = self.detailModel.paperQuestionDetail[indexPath.section - self.titlesArray.count].questionBank;
    LKPaperQuestionDetailModel *detailModel = self.qustionsArray[indexPath.section - self.titlesArray.count];
    LKQuestionBankDetailModel *model = detailModel.questionBank;
    if (indexPath.row == model.questionAnswer.count) {
        LKTestAnswerCell *ansercell = [tableView dequeueReusableCellWithIdentifier:@"LKTestAnswerCell"];
        ansercell.showLine = YES;
        NSString *rightAnser = @"正确答案：";
        for (LKQuestionAnswerDetailModel *ansmodel in model.questionAnswer) {
            if (ansmodel.isRight) {
                rightAnser = [rightAnser stringByAppendingString:ansmodel.answerName];
            }
        }
//        LKPaperQuestionDetailModel *anotherModel = self.detailModel.paperQuestionDetail[indexPath.section - self.titlesArray.count];
        LKPaperQuestionDetailModel *anotherModel = self.qustionsArray[indexPath.section - self.titlesArray.count];
        NSString *yoursAns = @"您的答案：";
        NSString *submitAnswer = [NSString judegeIsNullAndTransform:anotherModel.submitAnswer];
        yoursAns = [yoursAns stringByAppendingString:submitAnswer];
        [ansercell.yourBtn setTitle:yoursAns forState:UIControlStateNormal];
        [ansercell.righttn setTitle:rightAnser forState:UIControlStateNormal];
        return ansercell;
    }
    if (indexPath.row == model.questionAnswer.count + 1) {
        
        LKTestAnswerAnalysicCell *anycell = [tableView dequeueReusableCellWithIdentifier:@"LKTestAnswerAnalysicCell"];
        NSMutableAttributedString *str = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"答案解析：%@",model.analysis]];
        [str addAttribute:NSForegroundColorAttributeName value:blueDefault range:NSMakeRange(0, 4)];
        [str addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:15] range:NSMakeRange(0, 4)];
        anycell.contentLabel.attributedText = str;
        return anycell;
    }
    cell.detailModel = model.questionAnswer[indexPath.row];
    return cell;

}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
        return 78;
    }
    if (indexPath.section == 1 || indexPath.section == 2 || indexPath.section == 3 || indexPath.section == 4) {
            return 43;
    }
    if (indexPath.section == 5) {
        return 210;
    }
    if (indexPath.section == 6) {
        return UITableViewAutomaticDimension;
    }
//    LKQuestionBankDetailModel *model = self.detailModel.paperQuestionDetail[indexPath.section - self.titlesArray.count].questionBank;
    LKPaperQuestionDetailModel *detailModel = self.qustionsArray[indexPath.section - self.titlesArray.count];
    LKQuestionBankDetailModel *bankDetailModel = detailModel.questionBank;
    if (indexPath.row == bankDetailModel.questionAnswer.count) {
        return 50;
    }
    return UITableViewAutomaticDimension;

}
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView *view = [[UIView alloc] init];
    view.backgroundColor = cellHeaderBgColor;
    if (section >= self.titlesArray.count) {
        UIView *headerView = [[UIView alloc] init];
        headerView.backgroundColor = [UIColor whiteColor];
//        LKQuestionBankDetailModel *model = self.detailModel.paperQuestionDetail[section - self.titlesArray.count].questionBank;
        LKPaperQuestionDetailModel *detailModel = self.qustionsArray[section - self.titlesArray.count];
        LKQuestionBankDetailModel *model = detailModel.questionBank;
        NSString *questionTitle = [NSString stringWithFormat:@"【%@】%@",model.questionTypeTest,model.questionName];
        LKBaseLabel *label = [LKBaseLabel labelWithFrame:CGRectZero text:questionTitle textColor:COLOR_HEX(0x929292) font:[UIFont systemFontOfSize:15] textAlignment:NSTextAlignmentLeft backgroundColor:[UIColor whiteColor]];
        label.numberOfLines = 0;
        [headerView addSubview:label];
        [label mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(headerView.mas_left).offset(16);
            make.right.equalTo(headerView.mas_right).offset(-16);
            make.top.equalTo(headerView.mas_top).offset(21);
            make.bottom.equalTo(headerView.mas_bottom).offset(-21);
        }];
        UIView *topLineV = [[UIView alloc] init];
        topLineV.backgroundColor = cellHeaderBgColor;
        [headerView addSubview:topLineV];
        [topLineV mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.right.left.equalTo(headerView);
            make.height.mas_equalTo(1);
        }];
        return headerView;
    }
    return view;
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return section <= 6 ? 12: UITableViewAutomaticDimension;
}
-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    UIView *footerV = [[UIView alloc] init];
    footerV.backgroundColor = [UIColor redColor];
    return footerV;
}
-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0.0000000001;
}
-(NSArray *)titlesArray{
    if (!_titlesArray) {
        _titlesArray = @[@"",@"总题数",@"做对题数",@"做错题数",@"正确率",@"薄弱知识点",@"试题解析"];
    }
    return _titlesArray;
}

/**
 获取试卷的详情
 */
-(void)getTestpageDetailInformation{
    NSDictionary *param = [NSDictionary dictionaryWithObjectsAndKeys:self.paperId,@"Id", nil];
    [[LKNetDataManager defaultManager] sendRequestMethod:HTTPMethodPOST serverUrl:ServerlUrl apiPath:examnationDetailUrl header:[LKUserInforTool header] parameters:param progress:^(NSProgress * _Nullable progress) {
        
    } success:^(BOOL isSuccess, id  _Nullable responseObject) {
        LKTestDetailModel *model = [LKTestDetailModel modelWithDictionary:responseObject[@"result"]];
        self.detailModel = model;
        [self.qustionsArray addObjectsFromArray:self.detailModel.paperQuestionDetail];
        self.allQustionsArray = [self.detailModel.paperQuestionDetail copy];
        NSString *correctNumber = [NSString stringWithFormat:@"%ld",[self.detailModel.examinationAppointUserInfo.totalCount integerValue] - [self.detailModel.examinationAppointUserInfo.rightCount integerValue]];
        float v = 0.0;
        v =  ((float)[self.detailModel.examinationAppointUserInfo.rightCount integerValue])/ ((float)[self.detailModel.examinationAppointUserInfo.totalCount integerValue]) * 100;
        NSString *Vs = [NSString stringWithFormat:@"%.0f%%",v];
        [self.contentArray addObjectsFromArray:@[self.detailModel.examinationAppointUserInfo.totalCount,self.detailModel.examinationAppointUserInfo.rightCount,correctNumber,Vs]];
        [self.tableview reloadData];
        
    } failure:^(NSString * _Nullable errorMessage) {
        
    }];
}
-(NSMutableArray *)contentArray{
    if (!_contentArray) {
        _contentArray = [[NSMutableArray alloc] init];
    }
    return _contentArray;
}


/**
 滑动的头部设置

 @param scrollView tableview
 */
-(void)scrollViewDidScroll:(UIScrollView *)scrollView{
    if (scrollView.contentOffset.y > 544) {
        if (self.coverView) {
            return;
        }
    [UIView animateWithDuration:1 animations:^{
        NSLog(@"偏移量%lf",scrollView.contentOffset.y);
        currentOffset = scrollView.contentOffset.y;
            self.coverView = [[UIView alloc] init];
            self.coverView.backgroundColor = [UIColor whiteColor];
            [self.view addSubview:self.coverView];
            [self.view bringSubviewToFront:self.coverView];
            [self.coverView mas_makeConstraints:^(MASConstraintMaker *make) {
                make.left.right.equalTo(self.view);
                make.height.mas_equalTo(50);
                make.top.equalTo(self.view.mas_top).offset(NAVIGATION_BAR_HEIGHT);
            }];
            UILabel *introLabel = [[UILabel alloc] init];
            introLabel.textColor = cellTextColor;
            introLabel.text = @"试题解析";
            introLabel.font = [UIFont systemFontOfSize:15];
            introLabel.backgroundColor = [UIColor whiteColor];
            [self.coverView addSubview:introLabel];
            [introLabel mas_makeConstraints:^(MASConstraintMaker *make) {
                make.right.top.bottom.equalTo(self.coverView);
                make.left.equalTo(self.coverView).offset(37);
            }];
            self.correctBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        self.correctBtn.tag = 1000;
            _correctBtn.titleLabel.font = [UIFont systemFontOfSize:13];
            [_correctBtn setTitle:@"只显示错题" forState:UIControlStateNormal];
            [_correctBtn setTitle:@"显示全部" forState:UIControlStateSelected];
            [_correctBtn setTitleColor:blueDefault forState:UIControlStateSelected];
            [_correctBtn setTitleColor:blueDefault forState:UIControlStateNormal];
            [self.coverView addSubview:_correctBtn];
        self.correctBtn.selected = self.showSomeOrAll;
            [_correctBtn mas_makeConstraints:^(MASConstraintMaker *make) {
                make.right.equalTo(self.coverView).offset(-16);
                make.centerY.equalTo(self.coverView);
            }];
            [_correctBtn addTarget:self action:@selector(showSomeOrAll:) forControlEvents:UIControlEventTouchUpInside];
            
        }];
    }else{
        [self.coverView removeFromSuperview];
         self.coverView = nil;
    }

    
}


/**
 显示错题或者不显示

 @param btn 按钮
 */
-(void)showSomeOrAll:(UIButton *)btn{
    if (btn.tag == 1000) {
        
    }else{
        [self.coverView removeFromSuperview];
        self.coverView = nil;
    }
    btn.selected = !btn.selected;
    self.showSomeOrAll = !self.showSomeOrAll;
    if (!btn.selected) {
        for (NSInteger i = 0; i < self.qustionsArray.count; i++) {
            LKPaperQuestionDetailModel *model = self.qustionsArray[i];
            if ([model.isRight boolValue]) {
                [self.qustionsArray removeObject:model];
            }
        }
    }else{
        [self.qustionsArray removeAllObjects];
        [self.qustionsArray addObjectsFromArray:self.allQustionsArray];
    }
    [self.tableview reloadData];
    [self.tableview layoutIfNeeded];  //加上这段代码,
    [self.tableview setContentOffset:CGPointMake(0,543)];
    [self.tableview scrollToRow:0 inSection:6 atScrollPosition:UITableViewScrollPositionNone animated:YES];
}

-(NSMutableArray *)qustionsArray{
    if (!_qustionsArray) {
        _qustionsArray = [[NSMutableArray alloc] init];
    }
    return _qustionsArray;
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
